<template>
  <tm-app>
    <!-- 头部导航栏 -->
    <tm-navbar title="表单数据" :shadow="0">
    </tm-navbar>
    <view class="form-container">
      <template v-if="fields && fields.length > 0 && localFormData">
        <template v-for="field in fields" :key="field.id">
          <view class="form-item">
            <text
              class="form-label"
            >{{ field.name }}</text
            >
            <view class="form-content">
              <!-- 根据字段类型渲染不同的表单控件 -->
              <template
                v-if="getWidget(field.valueType, field.widget) === '数字框'"
              >
                <input
                  type="number"
                  :value="getFieldValue(field)"
                  placeholder="-"
                  class="form-input"
                  readonly
                />
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '文本框'"
              >
                <input
                  type="text"
                  :value="getFieldValue(field)"
                  placeholder="-"
                  class="form-input"
                  readonly
                />
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '多行文本框'"
              >
                <input
                  type="text"
                  :value="getFieldValue(field)"
                  placeholder="-"
                  class="form-input"
                  readonly
                />
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '单选框'"
              >
                <view
                  class="select-container"
                >
                  <text v-if="getFieldValue(field)">
                    <template v-if="field.lookups?.length">
                      {{ field.lookups.find(lookup=>lookup.value === getFieldValue(field))!.text }}
                    </template>
                    <template v-else>
                      <text class="loading">未添加该子选项</text>
                    </template>
                  </text>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '选择框'"
              >
                <view
                  class="select-container"
                >
                  <text v-if="getFieldValue(field)">
                    <template v-if="field.lookups?.length">
                      {{ field.lookups.find(lookup=>lookup.value === getFieldValue(field))!.text }}
                    </template>
                    <template v-else>
                      <text class="loading">未添加该子选项</text>
                    </template>
                  </text>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '多选框'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '引用选择框'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '多级选择框'"
              >
                <view
                  class="select-container"
                >
                  <text v-if="getFieldValue(field)">
                    <template v-if="field.lookups?.length">
                      {{ getFullPath(field.lookups, getFieldValue(field)) }}
                    </template>
                    <template v-else>
                      <text class="loading">未添加该子选项</text>
                    </template>
                  </text>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '操作组织'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '操作人'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '人员搜索框'"
              >
                <view
                  class="select-container"
                >
                  <text v-if="getFieldValue(field)">
                    {{ getUserDisplayName(field) || '未找到用户信息' }}
                  </text>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '单位搜索框'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '群组搜索框'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="
                  getWidget(field.valueType, field.widget) === '组织群搜索框'
                "
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '成员选择框'"
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="
                  getWidget(field.valueType, field.widget) === '内部机构选择框'
                "
              >
                <view
                  class="select-container"
                >
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '日期选择框'"
              >
                <view
                  class="select-container"
                >
                  <text v-if="getFieldValue(field)">{{ getFieldValue(field) }}</text>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '时间选择框'"
              >
                <view
                  class="select-container"
                >
                  <text v-if="getFieldValue(field)">{{ getFieldValue(field) }}</text>
                </view>
              </template>
            </view>
          </view>
        </template>
      </template>
      <view v-else class="empty-state">
        <tm-text label="暂无表单项" />
      </view>
    </view>
  </tm-app>
</template>
<script lang="ts" setup>
import { ref,onMounted,getCurrentInstance } from 'vue'
import { model } from '@/ts/base'
import { getWidget } from '@/utils/work'
import { XThing } from '@/ts/base/schema'
import { FieldModel } from '@/ts/base/model'
import orgCtrl from '@/ts/controller'
const fields = ref<FieldModel[]>([])
const localFormData = ref<XThing>()
const userInfoMap = ref(new Map())
const getUserDisplayName = (field: any) => {
  const value = getFieldValue(field)
  if (!value) return ''
  
  const userInfo = userInfoMap.value.get(value)
  return userInfo?.name || ''
}
onMounted(() => {
  const instance = getCurrentInstance()!.proxy
  const eventChannel = instance!.getOpenerEventChannel();
  eventChannel.on('formInfo', async (data) => {
    localFormData.value = data.localFormData
    fields.value = data.fields
    const userPromises: Promise<void>[] = []
    if(localFormData.value){
      Object.entries(data.localFormData).forEach(([key, value]) => {
        const field = fields.value.find(f => f.id === key)
        if (
          field &&
          typeof value === 'string' &&
          !userInfoMap.value.has(value) &&
          getWidget(field.valueType, field.widget) === '人员搜索框'
        ) {
          userPromises.push(getUserInfo(value))
        }
      })
      await Promise.all(userPromises)
    }
  })
})
const getUserInfo = async (userId: string) => {
  if (!userId) return null
  if (userInfoMap.value.has(userId)) {
    return userInfoMap.value.get(userId)
  }
  try {
    const res = await orgCtrl.user.findEntityAsync(userId)
    if (res) {
      userInfoMap.value.set(userId, res)
      return res
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
  return null
}
const getFieldValue = (field: any) => {
  if(!localFormData.value)return false
  return localFormData.value[field.id] ?? 
         localFormData.value['T' + field.id] ?? 
         localFormData.value[field.propId] ?? 
         localFormData.value['T' + field.propId]
}
const getFullPath = (lookups: model.XLookup[], targetValue: string): string => {
  const valueNode = lookups.find(item => item.value === targetValue)
  if (!valueNode) return ''

  const path: string[] = [valueNode.text]
  let currentNode = valueNode
  
  while (currentNode.parentId) {
    const parentNode = lookups.find(item => item.id === currentNode.parentId)
    if (!parentNode) break
    path.unshift(parentNode.text)
    currentNode = parentNode
  }
  
  return path.join('/')
}
</script>
<style lang="scss" scoped>
.form-container {
  .form-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 172rpx;
    background-color: #ffffff;
    margin-bottom: 10rpx;
    padding: 0 32rpx;

    .form-label {
      margin-bottom: 20rpx;
      font-size: 28rpx;
      color: #333;

      &.required::after {
        content: '*';
        color: #ff0000;
        margin-left: 4rpx;
      }
    }

    .form-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .form-input {
        flex: 1;
        height: 60rpx;
        font-size: 28rpx;
      }

      .placeholder {
        font-size: 28rpx;
        color: #00000066;
      }
    }
  }
}
</style>